<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺id" prop="shopId">
        <el-input v-model.trim="queryParams.shopId" placeholder="请输入店铺id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="店铺名字" prop="storeName">
        <el-input v-model.trim="queryParams.storeName" placeholder="请输入店铺名字" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="日期参数" prop="timeParam">
        <el-input
          v-model.trim="queryParams.timeParam"
          placeholder="请输入日期参数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="逻辑删除" prop="isDelete">
        <el-input
          v-model.trim="queryParams.isDelete"
          placeholder="请输入逻辑删除"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['automatic:subscription:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['automatic:subscription:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['automatic:subscription:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['automatic:subscription:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handledownloadByIds">下载</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="opendownload = true">批量下载</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="id != 0" plain size="mini" @click="pickEXCELID">选择订阅id</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 添加或修改平台报订阅对话框 -->
    <el-dialog :title="title" v-if="opendownload" :visible.sync="opendownload" width="500px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="备注列表" prop="platform">
          <el-select v-model="selectlabelList" multiple>
            <el-option v-for="dict in labelList" :label="dict" :value="dict" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitdownload">批量下载</el-button>
        <el-button @click="opendownload = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-table v-loading="loading" :data="subscriptionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="平台" align="center" prop="platform" />
      <el-table-column label="店铺id" align="center" prop="shopId" />
      <el-table-column label="店铺名字" align="center" prop="storeName" />
      <el-table-column label="最近N天" align="center" prop="timeParam" />
      <el-table-column label="开始日期" align="center" prop="startDate" />
      <el-table-column label="结束日期" align="center" prop="endDate" />
      <el-table-column label="是否激活" align="center" prop="activationStatus">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.activationStatus" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="报表类型" align="center" prop="reportType" />
      <!-- <el-table-column label="逻辑删除" align="center" prop="isDelete" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['automatic:subscription:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['automatic:subscription:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改平台报订阅对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="平台" prop="platform">
          <el-select v-model="form.platform">
            <el-option v-for="dict in dict.type.sys_sample_name" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
          <!-- <el-input v-model.trim="form.platform" placeholder="请输入平台" /> -->
        </el-form-item>
        <el-form-item label="店铺名字" prop="storeName">
          <!-- <el-input
            v-model.trim="form.storeName"
            placeholder="请输入店铺名字"
          /> -->
          <el-select filterable remote :remote-method="getselectShopList" v-model="form.storeName" value-key="shopId"
            @change="handleShopChange">
            <el-option v-for="dict in cascadeList" :key="dict.id" :label="dict.storeName" :value="dict" />
          </el-select>
        </el-form-item>
        <el-form-item label="店铺id" prop="shopId">
          <el-input :disabled="true" v-model.trim="form.shopId" placeholder="" clearable />
        </el-form-item>
        <el-form-item label="最近N天" prop="timeParam">
          <el-input v-model.trim="form.timeParam" placeholder="请输入最近N天" />
        </el-form-item>
        <!-- <el-form-item label="激活" prop="activationStatus">
          <el-input
            v-model.trim="form.activationStatus"
            placeholder="请输入激活"
          />
        </el-form-item> -->
        <el-form-item label="报表类型" prop="reportType">
          <el-input v-model.trim="form.reportType" placeholder="报表类型" />
        </el-form-item>
        <!-- <el-form-item label="逻辑删除" prop="isDelete">
          <el-input v-model.trim="form.isDelete" placeholder="请输入逻辑删除" />
        </el-form-item> -->
        <el-form-item label="开始日期" prop="remark">
          <!-- <el-input v-model.trim="queryParams.dataDate" placeholder="请输入日期" /> -->
          <el-date-picker clearable v-model="form.startDate" type="date" value-format="yyyy-MM-dd" placeholder="开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="remark">
          <!-- <el-input v-model.trim="queryParams.dataDate" placeholder="请输入日期" /> -->
          <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSubscription,
  getSubscription,
  delSubscription,
  addSubscription,
  updateSubscription,
  downloadByIds,
  downloadByLabel,
  selectLabelList
} from "@/api/automatic/subscription";
import {
  listBiPddPromotionDwd,
  getBiPddPromotionDwd,
  delBiPddPromotionDwd,
  addBiPddPromotionDwd,
  updateBiPddPromotionDwd,
  selectShopList,
} from "@/api/pdd/BiPddPromotionDwd";
export default {
  name: "Subscription",
  dicts: ["sys_sample_name"],
  props: {
    id: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      openSUBSCRIPTION: false,
      cascadeList: [],
      inputValue: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台报订阅表格数据
      subscriptionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopId: null,
        storeName: null,
        timeParam: null,
        activationStatus: null,
        reportType: null,
        isDelete: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      labelList: [],
      opendownload: false,
      selectlabelList: []

    };
  },
  watch: {
    id: {
      handler: function (newnew, oldold) {
        console.log("newnew", newnew);
        if (newnew) {
          // this.openSUBSCRIPTION = true
          // this.queryParams.id = newnew;
          // // this.queryParams.dateInType = "excel";
          // // this.form.id=newnew

          // this.getList();
          // this.gettableNameList();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.getList();
    selectLabelList().then((response) => {
      this.labelList = response
      // this.$modal.msgSuccess(response.msg);
      // this.getList();
    });
  },
  methods: {
    pickEXCELID() {
      // if (!this.queryParams.sqlId) {
      //   this.$modal.msgError("这个按钮是对外的");
      //   return;
      // }
      if (this.ids.length == 0) {
        this.$modal.msgError("请至少选择一条数据");
        return;
      } else {
        this.$emit("pickEXCELID", this.ids.toString());
      }
    },
    openLoading() {
      this.$modal.loading("正在加载，请稍候！");
    },
    submitdownload() {
      if (this.selectlabelList.length == 0) {
        this.$modal.msgError("请选择备注列表")
        return
      }
      console.log(JSON.stringify(this.selectlabelList));
      this.openLoading();
      downloadByLabel(this.selectlabelList).then((response) => {
        this.$modal.closeLoading();
        this.opendownload = false
        // this.$modal.msgSuccess(response.msg);
        this.getList();
      });
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.isActive === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '"规则吗？')
        .then(function () {
          return updateSubscription(row);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isActive = row.isActive === "0" ? "1" : "0";
        });
    },
    handledownloadByIds() {
      if (this.ids.length == 0) {
        this.$modal.msgError("请至少选择一条数据");
        return;
      }
      downloadByIds(this.ids).then((response) => {
        this.$modal.msgSuccess(response.msg);
        this.getList();
      });
    },
    handleShopChange(selectedObj) {
      // 直接获取完整对象
      console.log("选中店铺详情：", selectedObj);
      console.log("店铺ID：", selectedObj.shopId);
      console.log("店铺名：", selectedObj.storeName);
      this.form.shopId = selectedObj.shopId;
      this.form.storeName = selectedObj.storeName;
    },
    getselectShopList(key) {
      selectShopList({ storeName: key }).then((response) => {
        this.cascadeList = response;
      });
    },
    /** 查询平台报订阅列表 */
    getList() {
      this.loading = true;
      listSubscription(this.queryParams).then((response) => {
        this.subscriptionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shopId: null,
        storeName: null,
        timeParam: null,
        activationStatus: null,
        reportType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        remark: null,
      };
      this.resetForm("form");
      this.getselectShopList('')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台报订阅";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSubscription(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改平台报订阅";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateSubscription(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubscription(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除平台报订阅编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSubscription(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "automatic/subscription/export",
        {
          ...this.queryParams,
        },
        `subscription_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
